/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  JiYouXiuListActivity.java   
 * @Package com.jiyi.activity.main   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-28 下午5:44:54   
 * @version V1.0     
 */
package com.jiyi.activity.main;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.activity.zone.PersonInfoActivity;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.bean.zone.JiYouXiuBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.event.JiYouXiuListEvent;
import com.jiyi.inteface.WebApi;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: JiYouXiuListActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-28 下午5:44:54
 * 
 */
@SuppressLint("NewApi")
public class JiYouXiuListActivity extends ActivityBase implements OnRefreshListener {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	@BindView(R.id.mainList)
	RecyclerView mainList;
	private List<JiYouXiuBean> mJiYiXiuDatas = new ArrayList<JiYouXiuBean>();
	CommonAdapter adapter;

	// 加载进度条
	Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_jiyouxiu_list);
		ButterKnife.bind(this);
		init();
		EventBus.getDefault().register(this);
	}

	@Subscribe
	public void onJiYouXiuListEvent(JiYouXiuListEvent jiYouXiuListEvent) {
		int type = jiYouXiuListEvent.type;
		switch (type) {
		case JiYouXiuListEvent.ALL_JIYOUXIU_FRAGMENT:
			getData();
			break;

		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		hideDialog(dialog);
		super.onDestroy();
	}

	private void init() {
		setTop();
		setAdapter();
		getData();
	}

	/**
	 * @author: HYM
	 * @Title: getData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-7-24
	 */
	private void getData() {

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.JIYOUXIU_ALL_LIST, "",
				params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<JiYouXiuBean> temp = new Gson().fromJson(
										data,
										new TypeToken<List<JiYouXiuBean>>() {
										}.getType());
								mJiYiXiuDatas.clear();
								mJiYiXiuDatas.addAll(temp);
								adapter.notifyDataSetChanged();
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
						refreshLayout.setRefreshing(false);
					}
				});

	}

	/**
	 * @author: HYM
	 * @Title: setAdapter
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-7-24
	 */
	private void setAdapter() {
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);
		// 设置布局管理器
		mainList.setLayoutManager(new LinearLayoutManager(this));
		// 添加分割线
		mainList.addItemDecoration(new DividerItemDecoration(this,
				DividerItemDecoration.VERTICAL_LIST, getResources()
						.getDrawable(R.drawable.drvice_10)));
		// 初始化适配器
		adapter = new CommonAdapter<JiYouXiuBean>(this, R.layout.item_jiyouxiu,
				mJiYiXiuDatas) {
			@Override
			protected void convert(ViewHolder holder, final JiYouXiuBean t,
					final int position) {
				holder.setOnClickListener(R.id.ivLogo, new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(v.getContext(),
								PersonInfoActivity.class);
						intent.putExtra("id", t.getUser_id());
						startActivity(intent);

					}
				});
				holder.setText(R.id.tvUserName, t.getUser_name());
				holder.setText(R.id.tvCreateDate, t.getCreate_time());
				if (TextUtils.isEmpty(t.getContent())) {
					holder.setVisible(R.id.tvContent, false);
				} else {
					holder.setText(R.id.tvContent, t.getContent());
				}

				holder.setText(R.id.tvGoodNum, t.getLikeNum() + "");
				holder.setImage(R.id.ivLogo, t.getUser_logo());

				if (t.getImage() == null || t.getImage().size() <= 0) {
					holder.setVisible(R.id.gvXiu, false);
				} else {
					holder.setVisible(R.id.gvXiu, true);
					holder.setAdapter(R.id.gvXiu, t.getImage());
				}

				if (Integer.parseInt(t.getLikeNum()) > 0) {
					holder.setVisible(R.id.tvGoodNum, true);
					holder.setText(R.id.tvGoodNum, t.getLikeNum());
				} else {
					holder.setVisible(R.id.tvGoodNum, false);
				}

				if (t.getIs_praise()) {
					holder.setImageResource(R.id.ivGood,
							R.mipmap.icon_praise_on);
				} else {
					holder.setImageResource(R.id.ivGood,
							R.mipmap.icon_praise_normal);
				}

				holder.setOnClickListener(R.id.rlPraise, new OnClickListener() {

					@Override
					public void onClick(View v) {
						praise(t.getId(), position, t.getIs_praise());
					}
				});

			}
		};

		// recycleview设置适配器
		mainList.setAdapter(adapter);
	}

	private void setTop() {
		tvBack.setText("");
		tvTitle.setText("吉友秀");
		Drawable searchDraw = getResources().getDrawable(R.mipmap.icon_edit);
		searchDraw.setBounds(0, 0, searchDraw.getMinimumWidth(),
				searchDraw.getMinimumHeight());
		tvSearch.setCompoundDrawables(searchDraw, null, null, null);
		tvSearch.setText("发布");
	}

	@OnClick({ R.id.tvBack, R.id.tvSearch })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvSearch:
			Intent intent = new Intent(this, JiYouXiuFaBuActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	void praise(String id, final int position, Boolean flag) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		VolleyRequest.StringRequestPost(this, WebApi.JIYOUXIU_PRAISE, "",
				params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
								String data = obj.getString("data");
								JSONObject dataJson = new JSONObject(data);
								String praiseNum = dataJson
										.getString("likeNum");
								String is_praise = dataJson
										.getString("is_praise");
								mJiYiXiuDatas.get(position).setIs_praise(
										is_praise.equals("0") ? false : true);
								mJiYiXiuDatas.get(position).setLikeNum(
										praiseNum);
								// 获取返回 的点赞数和是否点赞标志，然后局部刷新
								// adapter.notifyItemChanged(position,mJiYiXiuDatas.size());
								adapter.notifyDataSetChanged();
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	@Override
	public void onRefresh() {
		getData();
	}
}
